package aom.ju.ss.utils

import android.app.Activity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.graphics.Paint
import android.net.Uri
import android.os.*
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.viewpager.widget.ViewPager
import aom.ju.ss.R
import aom.ju.ss.databinding.ViewPagerItemFragmentBinding
import aom.ju.ss.lpInterface.MyHttpCallBack
import aom.ju.ss.utils.TimeUtil.millisToStringShort
import aom.ju.ss.utils.http.LP_API
import aom.ju.ss.utils.http.OKHttpUtils
import aom.ju.ss.view.base.BaseFragment
import aom.ju.ss.view.shua.HomeShuaFragment
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.bumptech.glide.Glide
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import org.greenrobot.eventbus.util.ErrorDialogManager
import sun.misc.BASE64Decoder
import sun.misc.BASE64Encoder
import java.lang.reflect.Field
import java.util.regex.Matcher
import java.util.regex.Pattern
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec

//fun show(tv: Any) {
//    ToastUtils.show(tv)
//}
open class TextWatcherLP : TextWatcher {
    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {


    }

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
    }

    override fun afterTextChanged(s: Editable?) {
    }

}

/**
 * 计算距离
 */
fun TextView.juli(lng: String?, lat: String?) {
    val loc_lng = SpUtils.getString("lng").toDoubleOrNull()
    val loc_lat = SpUtils.getString("lat").toDoubleOrNull()
    if (loc_lng != null && loc_lat != null && lng?.toDoubleOrNull() != null && lat?.toDoubleOrNull() != null) {
        val distance = LocationUtils.getDistance(
            loc_lng,
            loc_lat,
            lng.toDouble(),
            lat.toDouble()
        )
        val s = LocationUtils.distanceFormat(distance)
        this.text = "距您:$s"
    } else {
        this.text = "距您:50.1公里"
    }

}

val handlers: Handler = Handler(Looper.getMainLooper()) { msg ->
    if (msg.what == 1993) {
        val vp = msg.obj as ViewPager

        vp.adapter?.count?.let { it ->
            if (vp.currentItem + 1 == it) {
                vp.currentItem = 0
            } else {
                vp.currentItem++
            }
            vp.jop(msg.arg1)

        }
    }

    false
}

/**
 * @param s 间隔时长
 *
 */
fun ViewPager.jop(s: Int) {
    this.adapter?.count?.let {
        val msg = Message()
        msg.obj = this
        msg.what = 1993
        msg.arg1 = s

        handlers.sendMessageDelayed(msg, s.toLong())
    }


}

fun callPhone(context: Context, phoneNum: String) {
    val intent = Intent(Intent.ACTION_DIAL)
    val data = Uri.parse("tel:$phoneNum")
    intent.data = data
    context.startActivity(intent)
}

fun Fragment.start(act: Class<*>, key: String = "") {
    val intent = Intent(this.activity, act)
    if (key.isNotEmpty()) {
        intent.putExtra("data", key)
    }
    this.startActivity(intent)
}

fun copy(mContext: Context, copyStr: String?): Boolean {
    return try {
        //获取剪贴板管理器
        val cm = mContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        // 创建普通字符型ClipData
        val mClipData = ClipData.newPlainText("Label", copyStr)
        // 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData)
        true
    } catch (e: java.lang.Exception) {
        false
    }
}


fun Activity.start(act: Class<*>, key: String = "") {
    val intent = Intent(this, act)
    if (key.isNotEmpty()) {
        intent.putExtra("data", key)
    }
    this.startActivity(intent)
}

fun Activity.start(act: Class<*>, key: ArrayList<String>) {
    val intent = Intent(this, act)
    if (key.isNotEmpty()) {
        intent.putExtra("data", key)
    }
    this.startActivity(intent)
}

val Activity.data: String
    get() {
        if (this.intent.hasExtra("data") && intent.getStringExtra("data") != null) {
            return this.intent.getStringExtra("data")!!
        }
        return ""
    }

val Activity.arr: ArrayList<String>
    get() {
        if (this.intent.hasExtra("data") && intent.getStringArrayListExtra("data") != null) {
            return this.intent.getStringArrayListExtra("data")!!
        }
        return arrayListOf()
    }

fun Activity.startResult(act: Class<*>, requestCode: Int, key: String = "") {

    val intent = Intent(this, act)
    if (key.isNotEmpty()) {
        intent.putExtra("data", key)
    }
    this.startActivityForResult(intent, requestCode)
}

fun Activity.startResult(act: Class<*>, requestCode: Int,  key: ArrayList<String>) {

    val intent = Intent(this, act)
    if (key.isNotEmpty()) {
        intent.putExtra("data", key)
    }
    this.startActivityForResult(intent, requestCode)
}

fun TextView.zhx() {
    this.paint.flags =
        Paint.STRIKE_THRU_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG     //中划线

}

fun TextView.xhx() {
    this.paint.flags =
        Paint.UNDERLINE_TEXT_FLAG    //下划线
}

fun ViewPager.show(arrayList: MutableList<String>, s: FragmentManager) {
    val fs = arrayListOf<ViewPagerItemFragment>()
    for (a in arrayList) {
        fs.add(ViewPagerItemFragment.getMys(a))
    }

    this.adapter = object : FragmentStatePagerAdapter(s, 1) {
        override fun getCount(): Int {
            return arrayList.size
        }

        override fun getItem(position: Int): Fragment {
            return fs[position]
        }
    }
    this.offscreenPageLimit = arrayList.size

}

fun ListToStr(descImg: MutableList<String>): String {
    var s = ""
    for (a in descImg) {
        if (s != "") {
            s += ","
        }
        s += a
    }

    return s

}

/**
 * 显示/隐藏  占位置
 */
fun View.VIV(tv: Boolean) {
    visibility = if (tv) View.VISIBLE else View.INVISIBLE
}

/**
 * 显示/消失
 */
fun View.VG(vg: Boolean) {
    visibility = if (vg) View.VISIBLE else View.GONE
}

fun SmartRefreshLayout.Fin() {
    this.finishRefresh()
    this.finishLoadMore()
}

val TextView.send: Unit
    get() {
        val tv = this
        val count = object : CountDownTimer(60 * 1000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                tv.text = (millisUntilFinished / 1000).toString()
                tv.isClickable = false
            }

            override fun onFinish() {
                tv.text = "获取验证码"
                tv.isClickable = true
            }

        }
        count.start()

    }

/**
 * 订单倒计时
 */
fun TextView.djs(long: Long = 30 * 60 * 1000, def: String = "订单已过期", showTv: String = "支付剩余时间:") {
    val tv = this
    val count = object : CountDownTimer(long, 1000) {
        override fun onTick(millisUntilFinished: Long) {
            tv.text = showTv + millisToStringShort(millisUntilFinished)
            tv.isClickable = false
        }

        override fun onFinish() {
            tv.text = def
            tv.isClickable = true
        }

    }
    count.start()

}

fun EditText.passWordeq(ed: EditText): Boolean {
    if (this.text.toString().length < 6) {
        "请输入6位密码".show
        return false
    }
    if (this.text.toString() != ed.text.toString()) {
        "两次密码输入不一致".show
        return false
    }
    return true
}

val EditText.isCode: Boolean
    get() {

        if (this.text.toString().length != 4) {
            "请输入4位验证码".show()
            return false
        }
        return true
    }

fun Activity.sendCode(phone: TextView, bt: TextView) {

    if (phone.isPhone) {
        bt.send
        OKHttpUtils(this)
            .SetApiUrl(LP_API.SEND_CODE)
            .SetKey("phone")
            .SetValue(
                phone.text.toString()
            )
            .POST(object : MyHttpCallBack {
                override fun ok(jsonString: String?, httpTY: String?) {
                    "发送成功".show
                }

                override fun error(e: String?, jsonString: String?, httpTY: String?) {
                    e?.show
                }

            })
    }

}

val TextView.isPhone: Boolean
    get() {
        if (null == this.text || "" == this.text.toString()) {
            "请输入手机号".show()
            return false
        }
        if (this.text.toString().length != 11) {
            "请输入11手机号".show()
            return false
        }
        return true
    }

val EditText.isEmail: Boolean
    get() {
        if (null == this.text || "" == this.text.toString()) {
            "请输入邮箱号".show()
            return false
        }
        val regEx1 =
            "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$"
        val p: Pattern = Pattern.compile(regEx1)
        val m: Matcher = p.matcher(this.text.toString())
        if (!m.matches()) {
            "请输入正确的邮箱号".show()
            return false
        }
        return true
    }


val Int.toPx: Int
    get() {
        val scale: Float = BaseApplication.getInstance().resources.displayMetrics.density
        return (this * scale + 0.5f).toInt()
    }


/**
 * 设置状态栏文字 黑色 或者白色  true 为白色
 */
var Activity.topTxtWhite: Boolean
    get() = true
    set(boo) {
        val decorView: View = this.window.decorView
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            decorView.systemUiVisibility =
                (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE // 白色文字
                        or if (boo) View.SYSTEM_UI_FLAG_VISIBLE else View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR)
        } else {
            decorView.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        }
    }


val Int.dp: Int
    get() {
        val scale: Float = BaseApplication.getInstance().resources.displayMetrics.density
        return (this * scale + 0.5f).toInt()
    }


val String.log: Unit
    get() {
        LogUtils.e(this)
    }
var toasts: Toast? = null

val String.show: Unit
    get() {
        if (this.isEmpty() || this.length > 100) {
            return
        }
        if (toasts == null) {
            toasts = Toast.makeText(BaseApplication.getInstance(), null, Toast.LENGTH_SHORT)

        }
        try {
            toasts!!.setText(this)
            toasts!!.show()
        } catch (c: Exception) {
            LogUtils.e(c.message)
        }
    }

fun String.show() {
    if (this.isEmpty() || this.length > 100) {
        return
    }
    if (toasts == null) {
        toasts = Toast.makeText(BaseApplication.getInstance(), null, Toast.LENGTH_SHORT)

    }
    try {
        toasts!!.setText(this)
        toasts!!.show()
    } catch (c: Exception) {
        LogUtils.e(c.message)
    }
}

fun String.showLong() {
    if (this.isEmpty() || this.length > 100) {
        return
    }
    if (toasts == null) {
        toasts = Toast.makeText(BaseApplication.getInstance(), null, Toast.LENGTH_LONG)

    }
    try {
        toasts!!.setText(this)
        toasts!!.show()
    } catch (c: Exception) {
        LogUtils.e(c.message)
    }
}

/**
 * @param context
 * @param time     秒
 * @param listener
 */
fun getLocationByGaode(context: Activity, listener: AMapLocationListener) {
    val locationClient = AMapLocationClient(context)
    val mLocationOption = AMapLocationClientOption()
    mLocationOption.isOnceLocation = true //只定位一次
    locationClient.setLocationListener(listener)
    mLocationOption.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
    locationClient.setLocationOption(mLocationOption)
    locationClient.startLocation()

}

class ViewPagerItemFragment : BaseFragment() {
    private lateinit var binding: ViewPagerItemFragmentBinding

    companion object {
        fun getMys(u: String): ViewPagerItemFragment {
            val f = ViewPagerItemFragment()
            val bu = Bundle()
            bu.putString("img", u)
            f.arguments = bu
            return f
        }
    }

    override fun init() {
        binding = viewBinding as ViewPagerItemFragmentBinding


        Glide.with(this)
            .load(arguments?.getString("img"))
            .centerCrop()
            .into(binding.img)
    }

    override fun getLay(): Int {
        return R.layout.view_pager_item_fragment
    }


}


private val sKey = "1234567890123456"
private val ivParameter = "1571925183403747"

// 加密
fun encrypt(sSrc: String): String? {
    val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
    val raw = sKey.toByteArray()
    val skeySpec = SecretKeySpec(raw, "AES")
    val iv = IvParameterSpec(ivParameter.toByteArray()) // 使用CBC模式，需要一个向量iv，可增加加密算法的强度
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv)
    val encrypted = cipher.doFinal(sSrc.toByteArray(charset("utf-8")))
    return BASE64Encoder().encode(encrypted) // 此处使用BASE64做转码。
}

// 解密
fun decrypt(sSrc: String?): String? {
    return try {
        val raw: ByteArray = sKey.toByteArray(charset("ASCII"))
        val skeySpec =
            SecretKeySpec(raw, "AES")
        val cipher =
            Cipher.getInstance("AES/CBC/PKCS5Padding")
        val iv =
            IvParameterSpec(ivParameter.toByteArray())
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv)
        val encrypted1 = BASE64Decoder().decodeBuffer(sSrc) // 先用base64解密
        val original = cipher.doFinal(encrypted1)
        String(original)//"utf-8"
    } catch (ex: java.lang.Exception) {
        null
    }

    fun String.log() {
        LogUtils.e(this)
    }
}

